<?php
namespace admin\controllers;
use admin\models\Admin;
use admin\models\AuthAssignment;
use admin\models\Relation;
use admin\models\UserComment;
use admin\models\UserDetail;
use admin\models\UserExperience;
use admin\models\UserExtra;
use admin\models\UserFamily;
use admin\models\UserHealth;
use admin\models\UserIll;
use admin\models\UserInfo;
use admin\models\UserMeeting;
use admin\models\UserPhoto;
use admin\models\UserRequirements;
use admin\models\Zone;
use Faker\Provider\File;
use yii\base\Exception;
use yii\helpers\FileHelper;
use yii\web\Response;
use yii\data\Pagination;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\VarDumper;
use yii\web\UploadedFile;
use yii\widgets\ActiveForm;

/**
 * Created by PhpStorm.
 * User: 沈小鱼
 * Date: 2016/8/6
 * Time: 8:13
 */
class UserController extends BaseController{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['index','view','create','areachange','del','recover','valid-form','upload','update','info','search'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'upload' => ['post'],
                ],
            ],
        ];
    }

    public function actionIndex(){
        $searchArr = Yii::$app->request->get('search');
        $fieldArr = Yii::$app->request->get('field');
        $admin = Yii::$app->user->identity;
        $admins = Admin::find()->where($admin->ma_type==2 ? 'ma_type>0':'ma_type>'.$admin->ma_type.' or ma_id='.$admin->ma_id)->asArray()->all();
        $adIdArr = array_column($admins,'ma_id');
        $adIds = implode(',',$adIdArr);
        $province = ArrayHelper::map(Zone::GetAllProvince(),'id','name');
        $city = [];
        $district = [];
        $me_postion='';
        if(!empty($fieldArr['province'])){
            $me_postion.=Zone::find()->where('id='.$fieldArr['province'])->one()->name.';';
            $city = ArrayHelper::map(Zone::find()->where('parentid='.$fieldArr['province'].' and leveltype=2 and status<>0')->asArray()->all(),'id','name');
        }
        if(!empty($fieldArr['city'])){
            $me_postion.=Zone::find()->where('id='.$fieldArr['city'])->one()->name.';';
            $district = ArrayHelper::map(Zone::find()->where('parentid='.$fieldArr['city'].' and leveltype=3 and status<>0')->asArray()->all(),'id','name');
        }
        if(!empty($fieldArr['district'])){
            $me_postion.=Zone::find()->where('id='.$fieldArr['district'])->one()->name;
        }
        $edu = [1=>'初中以上',2=>'高中以上',3=>'大专以上',4=>'本科以上'];
        $eduArr = ['文盲','初中','高中','本科','大专','博士','硕士'];
        $data = UserInfo::find()->where('mo_id in ('.$adIds.')')->joinWith('owner')->joinWith('photos')->joinWith('extras')->joinWith('details');
        if(!empty($searchArr)){
            foreach($searchArr as $key=>$value){
                $data->andFilterWhere(['like',$key,$value]);
            }
        }
        if(!empty($me_postion)){
            $data->andFilterWhere(['like','me_postion',$me_postion]);
        }
        if(!empty($fieldArr['mi_edu'])){
            $edustr = "('".implode("','",array_slice($eduArr,$fieldArr['mi_edu']))."')";
            $data->andFilterWhere(['and',"mi_edu in ".$edustr]);
        }
        if(!empty($fieldArr['minage'])){
            $data->andFilterWhere(['>=','mi_age',$fieldArr['minage']]);
        }
        if(!empty($fieldArr['maxage'])){
            $data->andFilterWhere(['<=','mi_age',$fieldArr['maxage']]);
        }
        if(!empty($fieldArr['md_isowner'])){
            $data->andFilterWhere(['and','md_isowner='.(int)$fieldArr['md_isowner']]);
        }
        if(!empty($fieldArr['md_hascar'])){
            $data->andFilterWhere(['and','md_hascar='.(int)$fieldArr['md_hascar']]);
        }
        $pages = new Pagination([
            'totalCount' =>$data->count(),
            'pageSize' => '12',
            'pageSizeParam' => false,
        ]);
        $users = $data->offset($pages->offset)->limit($pages->limit)->all();
        $userInfo = new UserInfo(['scenario'=>'add']);
        $userExtra = new UserExtra(['scenario'=>'add']);
        $userDetail = new UserDetail(['scenario'=>'add']);
        $userHealth = new UserHealth();
        $defaultPrivince = ArrayHelper::map(Zone::GetAllProvince(),'id','name');
        $defaultCity = ArrayHelper::map(Zone::GetDefaultCity(),'id','name');
        $defaultDistrict = ArrayHelper::map(Zone::GetDefaultDistrict(),'id','name');
        $userInfo->mi_sex = '男';
        if(empty($searchArr)){
            return $this->render('index',[
                'users'=>$users,
                'pages'=>$pages,
                'info'=>$userInfo,
                'extra'=>$userExtra,
                'health'=>$userHealth,
                'detail'=>$userDetail,
                'privinces'=>$defaultPrivince,
                'cities'=>$defaultCity,
                'districts'=>$defaultDistrict,
                'privinceArr'=>$province,
                'cityArr'=>$city,
                'districtArr'=>$district,
                'eduArr'=>$edu,
                'searchArr'=>$searchArr,
                'fieldArr'=>$fieldArr,
            ]);
        }else{
            return $this->renderPartial('index',[
                'users'=>$users,
                'pages'=>$pages,
                'info'=>$userInfo,
                'extra'=>$userExtra,
                'health'=>$userHealth,
                'detail'=>$userDetail,
                'privinces'=>$defaultPrivince,
                'cities'=>$defaultCity,
                'districts'=>$defaultDistrict,
                'privinceArr'=>$province,
                'cityArr'=>$city,
                'districtArr'=>$district,
                'eduArr'=>$edu,
                'searchArr'=>$searchArr,
                'fieldArr'=>$fieldArr,
            ]);
        }
    }

    public function actionSearch(){
        $user = Yii::$app->user->identity;
        if(empty($user)){
            $this->goHome();
        }else{
            $table = Yii::$app->request->get('table');
            $key = Yii::$app->request->get('key');
            $val = Yii::$app->request->get('val');
            $sql = "select $key from $table where $key like '%$val%'";
            $values = Yii::$app->db->createCommand($sql)->queryAll();
            if(empty($values)){
                $data = [];
            }else{
                $data = array_unique(array_column($values,$key));
            }
            return $this->showResult(200,'成功',$data);
        }
    }

    public function actionValidForm(){
        $id = Yii::$app->request->get('id');
        Yii::$app->response->format = Response::FORMAT_JSON;
        $infoArr = Yii::$app->request->post('UserInfo');
        $extraArr = Yii::$app->request->post('UserExtra');
        $detailArr = Yii::$app->request->post('UserDetail');
        $healthArr = Yii::$app->request->post('UserHealth');
        if(empty($detailArr['md_child'])){
            $detailArr['md_child'] = null;
        }
        if(empty($detailArr['md_child_belong'])){
            $detailArr['md_child_belong'] = null;
        }
        $userInfo = new UserInfo(['scenario'=>empty($id) ?'add':'update']);
        $userExtra = new UserExtra(['scenario'=>empty($id) ?'add':'update']);
        $userDetail = new UserDetail(['scenario'=>empty($id) ?'add':'update']);
        $userHealth = new UserHealth();
        if(!empty($id)){
            $userInfo->mi_id = $id;
            $userExtra->mu_id = $id;
            $userDetail->mu_id = $id;
            $userHealth->mu_id = $id;
        }
        $userInfo->attributes = $infoArr;
        $userExtra->attributes = $extraArr;
        $userDetail->attributes = $detailArr;
        $userHealth->attributes = $healthArr;
        return ActiveForm::validate($userInfo,$userExtra,$userDetail,$userHealth);
    }

    public function actionAreachange(){
        $user = Yii::$app->user->identity;
        if(empty($user)){
            return $this->showResult(302,'登陆信息已失效，请重新登录');
        }
        $level = Yii::$app->request->post('level');
        $area_id = Yii::$app->request->post('area_id');
        $res = $this->changeDrowList($level,$area_id);
        if(empty($res)){
            return $this->showResult(301,'没有下级区域啦');
        }else{
            $result = [
                'cities'=>$res[0],
                'districts'=>$res[1],
            ];
            return $this->showResult(200,'成功',$result);
        }
    }

    public function changeDrowList($level,$id){
        $cities = [];
        $districts = [];
        if($level==1){
            $cityArr = Zone::find()->where(['and','parentid='.$id,'leveltype=2','status<>0'])->asArray()->all();
            $cities = ArrayHelper::map($cityArr,'id','name');
            $keys = array_keys($cities);
            $districtArr = Zone::find()->where(['and','parentid='.$keys[0],'leveltype=3','status<>0'])->asArray()->all();
            $districts = ArrayHelper::map($districtArr,'id','name');
        }elseif($level==2){
            $districtArr = Zone::find()->where(['and','parentid='.$id,'leveltype=3','status<>0'])->asArray()->all();
            $districts = ArrayHelper::map($districtArr,'id','name');
        }
        if(empty($cities)&&empty($districts)){
            return [];
        }else{
            return [$cities,$districts];
        }
    }

    public function actionCreate(){
        $admin_id = Yii::$app->user->identity->getId();
        if(empty($admin_id)){
            return $this->showResult(302,'登陆信息已失效，请重新登录');
        }
        $infoArr = Yii::$app->request->post('UserInfo');
        $extraArr = Yii::$app->request->post('UserExtra');
        $detailArr = Yii::$app->request->post('UserDetail');
        $healthArr = Yii::$app->request->post('UserHealth');
        if(empty($detailArr['md_child'])){
            $detailArr['md_child'] = null;
        }
        if(empty($detailArr['md_child_belong'])){
            $detailArr['md_child_belong'] = null;
        }
        $userInfo = new UserInfo(['scenario'=>'add']);
        $userExtra = new UserExtra(['scenario'=>'add']);
        $userDetail = new UserDetail(['scenario'=>'add']);
        $userHealth = new UserHealth();
        $userInfo->attributes = $infoArr;
        $userExtra->attributes = $extraArr;
        $userDetail->attributes = $detailArr;
        $userHealth->attributes = $healthArr;
        $transaction = Yii::$app->db->beginTransaction();
        try{
            $userInfo->mo_id = $admin_id;
            $userInfo->mi_age = date('Y')-substr($infoArr['mi_birth'],0,4)+1;
            $userInfo->created_time = date('Y-m-d H:i:s');
            $userInfo->updated_time = date('Y-m-d H:i:s');
            $userInfo->mi_status = 1;
            if(!$userInfo->save()){
                throw new Exception('写入用户信息失败');
            }
            $userExtra->mu_id = $userInfo->mi_id;
            $userDetail->mu_id = $userInfo->mi_id;
            $userHealth->mu_id = $userInfo->mi_id;
            if(!$userExtra->save()){
                throw new Exception('写入用户其余信息失败');
            }
            if(!$userDetail->save()){
                throw new Exception('写入用户详细信息失败');
            }
            if(!$userHealth->save()){
                throw new Exception('写入用户健康信息失败');
            }
            $transaction->commit();
            return $this->showResult(200,'保存成功',$userInfo->mi_id);
        }catch (Exception $e){
            $transaction->rollBack();
            return $this->showResult(400,$e->getMessage());
        }
    }

    public function actionView(){
        $user_id = Yii::$app->request->get('id');
        $user = UserInfo::findOne($user_id);
        $defaultPrivince = ArrayHelper::map(Zone::GetAllProvince(),'id','name');
        $defaultCity = ArrayHelper::map(Zone::GetDefaultCity(),'id','name');
        $defaultDistrict = ArrayHelper::map(Zone::GetDefaultDistrict(),'id','name');
        $userPhoto = new UserPhoto();
        $meetting = new UserMeeting();
        $others = ArrayHelper::map(UserInfo::find()->where('mi_id<>'.$user_id." and mi_sex<>'".$user['mi_sex']."'")->asArray()->all(),'mi_id','mi_name');
        $ill = new UserIll();
        $userFamily = new UserFamily();
        $relations = Relation::getRelations();
        $experience = new UserExperience();
        $comment = new UserComment();
        $requirement = new UserRequirements();
        return $this->render('view',[
            'user'=>$user,
            'photo'=>$userPhoto,
            'privinces'=>$defaultPrivince,
            'meetModel'=>$meetting,
            'cities'=>$defaultCity,
            'districts'=>$defaultDistrict,
            'targets'=>$others,
            'ill'=>$ill,
            'family'=>$userFamily,
            'relation'=>$relations,
            'experience'=>$experience,
            'comment'=>$comment,
            'requirement'=>$requirement,
        ]);
    }

    public function actionInfo(){
        $user_id = Yii::$app->request->get('user_id');
        $user = UserInfo::findOne($user_id);
        return $this->renderPartial('info',[
            'user'=>$user,
            ]);
    }

    public function actionUpdate(){
        $admin_id = Yii::$app->user->identity->getId();
        if(empty($admin_id)){
            return $this->showResult(302,'登陆信息已失效，请重新登录');
        }
        $id = Yii::$app->request->get('id');
        if(empty($id)){
            return $this->showResult(301,'未获取到客户信息');
        }
        $userInfo = UserInfo::findOne($id);
        if(empty($userInfo)){
            return $this->showResult(301,'未获取到客户信息');
        }
        $infoArr = Yii::$app->request->post('UserInfo');
        $extraArr = Yii::$app->request->post('UserExtra');
        $detailArr = Yii::$app->request->post('UserDetail');
        $healthArr = Yii::$app->request->post('UserHealth');
        $photoArr = Yii::$app->request->post('UserPhoto');
        if(empty($detailArr['md_child'])){
            $detailArr['md_child'] = null;
        }
        if(empty($detailArr['md_child_belong'])){
            $detailArr['md_child_belong'] = null;
        }
        $userExtra = $userInfo->extras;
        $userDetail = $userInfo->details;
        $userHealth = $userInfo->healths;
        $userPhoto = $userInfo->photos;
        if(empty($userPhoto)){
            $userPhoto = new UserPhoto();
        }else{
            $photoArr['mp_main'] = empty($photoArr['mp_main'])&&!empty($userPhoto->mp_main) ? $userPhoto->mp_main:$photoArr['mp_main'];
        }
        $userInfo->attributes = $infoArr;
        $userExtra->attributes = $extraArr;
        $userDetail->attributes = $detailArr;
        $userHealth->attributes = $healthArr;
        $userPhoto->attributes = $photoArr;
        $transaction = Yii::$app->db->beginTransaction();
        try{
            $userInfo->mi_age = date('Y')-substr($infoArr['mi_birth'],0,4)+1;
            $userInfo->updated_time = date('Y-m-d H:i:s');
            if(!$userInfo->save()){
                throw new Exception('更新用户信息失败');
            }
            $userExtra->mu_id = $userInfo->mi_id;
            $userDetail->mu_id = $userInfo->mi_id;
            $userHealth->mu_id = $userInfo->mi_id;
            $userPhoto->mu_id = $id;
            if(!$userExtra->save()){
                throw new Exception('更新用户其余信息失败');
            }
            if(!$userDetail->save()){
                throw new Exception('更新用户详细信息失败');
            }
            if(!$userHealth->save()){
                throw new Exception('更新用户健康信息失败');
            }
            if(!$userPhoto->save()){
                throw new Exception('更新用户照片信息失败');
            }
            $transaction->commit();
            return $this->showResult(200,'保存成功',Yii::$app->params['img_path'].$photoArr['mp_main']);
        }catch (Exception $e){
            $transaction->rollBack();
            return $this->showResult(400,$e->getMessage());
        }
    }

    public function actionDel(){
        $user_id = Yii::$app->user->identity->getId();
        if(empty($user_id)){
            return $this->showResult(302,'用户登录信息失效');
        }
        $mi_id = Yii::$app->request->post('mi_id');
        if(empty($mi_id)){
            return $this->showResult(301,'读取数据发生错误');
        }
        $userInfo = UserInfo::findOne(['mi_id'=>$mi_id]);
        if(empty($userInfo)){
            return $this->showResult(301,'未获取到该用户的信息');
        }
        $userInfo->mi_status=0;
        $userInfo->updated_time = date('Y-m-d H:i:s',time());
        if($userInfo->save()){
            return $this->showResult(200,'删除成功');
        }else{
            return $this->showResult(400,'删除失败，请重试');
        }
    }

    public function actionRecover(){
        $user_id = Yii::$app->user->identity->getId();
        if(empty($user_id)){
            return $this->showResult(302,'用户登录信息失效');
        }
        $mi_id = Yii::$app->request->post('mi_id');
        if(empty($mi_id)){
            return $this->showResult(301,'读取数据发生错误');
        }
        $userInfo = UserInfo::findOne(['mi_id'=>$mi_id]);
        if(empty($userInfo)){
            return $this->showResult(301,'未获取到该用户的信息');
        }
        $userInfo->mi_status=1;
        $userInfo->updated_time = date('Y-m-d H:i:s',time());
        if($userInfo->save()){
            return $this->showResult(200,'恢复成功');
        }else{
            return $this->showResult(400,'恢复失败，请重试');
        }
    }

    public function actionUpload(){
        $admin = Yii::$app->user->identity;
        if(empty($admin)){
            echo json_encode([
                'imageUrl'=>'',
                'error'=>'登录信息失效，请重新登录',
            ]);
            exit;
        }
        $id = Yii::$app->request->post('id');
        $userPhoto = new UserPhoto();
        if(Yii::$app->request->isPost) {
            $image = UploadedFile::getInstance($userPhoto, 'mp_main');
            $path = 'photo/users/'.$id;
            if(!is_dir($path) || !is_writable($path)){
                FileHelper::createDirectory($path,0777,true);
            }
            $filePath = $path  . '/' . $id . '_' .md5(uniqid() . mt_rand(10000,99999999)) . '.' . $image->extension;
            if( $image->saveAs($filePath)){
                echo json_encode([
                    'imageUrl'=>$filePath,
                    'error'=>'',
                ]);
                exit;
            }else{
                echo json_encode([
                    'imageUrl'=>'',
                    'error'=>'保存图片失败，请重试',
                ]);
                exit;
            }
        }else{
            echo json_encode([
                'imageUrl'=>'',
                'error'=>'未获取到图片信息',
            ]);
            exit;
        }
    }

}